<template>
  <form action="/">
    <van-search
        v-model="value"
        show-action
        placeholder="请输入搜索标签"
        @search="onSearch"
        @cancel="onCancel"
    />
  </form>

  <van-divider content-position="left">已选择标签</van-divider>
  <van-row gutter="16" style="padding: 0 16px">
    <van-col v-for=" tag in activeIds">
    <van-tag  closeable  :key="id" size="medium" type="primary"  @close="deleteTag(tag)">
      {{ getTagNameById(tag) }}
    </van-tag>
    </van-col>
  </van-row>

  <van-divider content-position="left">可选择标签</van-divider>
  <van-tree-select
      v-model:active-id="activeIds"
      v-model:main-active-index="activeIndex"
      :items="items"
  />

</template>


<script setup lang="ts">
import {ref} from "vue";

const value = ref('');


//分类选择
const activeIds = ref([]);
const activeIndex = ref(0);
const oldItems = ref([
  {
    text: '性别',
    children: [
      {text: '男', id: 1},
      {text: '女', id: 2}
    ]
  },
  {
    text: '游戏',
    children: [
      {text: '王者荣耀', id: 3},
      {text: '英雄联盟', id: 4}
    ]
  }
])

let items = ref(oldItems.value);

const getTagNameById = (id: number) => {
  for (const item of oldItems.value) {
    const child = item.children.find(child => child.id === id);
    if (child) {
      return child.text;
    }
  }
  return '';
}

const deleteTag = (tag:Object) => {
  activeIds.value = activeIds.value.filter(item => {
    return item !== tag;
  });
}


const onSearch = () => {
  items.value = items.value.map(parent => {
    return {
      ...parent,
      children: parent.children.filter(child => child.text.includes(value.value))
    };
  });
};


const onCancel = () => {
  items.value = oldItems.value;
}
</script>

<style scoped>
</style>